const express = require('express');
const router = express.Router();
const { check, query, validationResult } = require('express-validator');
const { protect } = require('../../middleware/auth');
const FoodGI = require('../../models/FoodGI');
const User = require('../../models/User');
const DietMeal = require('../../models/DietMeal');

/**
 * @route   GET api/food/gi
 * @desc    获取所有食物GI值数据
 * @access  Private
 */
router.get('/gi', protect, async (req, res) => {
  try {
    const foods = await FoodGI.find().sort({ name: 1 });
    res.json({
      success: true,
      count: foods.length,
      data: foods
    });
  } catch (err) {
    console.error('获取食物GI值数据失败:', err.message);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

/**
 * @route   GET api/food/search
 * @desc    搜索食物
 * @access  Private
 */
router.get('/search', [
  protect,
  query('keyword').optional().isString().trim(),
  query('category').optional().isString().trim()
], async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({
      success: false,
      errors: errors.array()
    });
  }

  try {
    const { keyword, category } = req.query;
    
    // 构建查询条件
    const query = {};
    
    if (keyword) {
      query.name = { $regex: keyword, $options: 'i' };
    }
    
    if (category && category !== 'all') {
      query.category = category;
    }
    
    const foods = await FoodGI.find(query).sort({ name: 1 });
    
    res.json({
      success: true,
      count: foods.length,
      data: foods
    });
  } catch (err) {
    console.error('搜索食物失败:', err.message);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

/**
 * @route   GET api/food/recommend
 * @desc    获取食物推荐
 * @access  Private
 */
router.get('/recommend', protect, async (req, res) => {
  try {
    const userId = req.user.id;
    
    // 获取用户营养目标
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '未找到用户'
      });
    }
    
    // 获取用户今日膳食记录
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    const meals = await DietMeal.find({
      user: userId,
      date: {
        $gte: today,
        $lt: tomorrow
      }
    });
    
    // 计算今日已摄入的营养素
    const consumed = {
      calories: 0,
      carbs: 0,
      protein: 0,
      fat: 0,
      fiber: 0
    };
    
    meals.forEach(meal => {
      consumed.calories += meal.calories || 0;
      consumed.carbs += meal.carbs || 0;
      consumed.protein += meal.protein || 0;
      consumed.fat += meal.fat || 0;
      consumed.fiber += meal.fiber || 0;
    });
    
    // 获取用户营养目标
    const nutritionTarget = user.nutritionTarget || {};
    const targets = {
      calories: nutritionTarget.calories || 2000,
      carbs: nutritionTarget.carbs || 250,     // 单位：克
      protein: nutritionTarget.protein || 75,  // 单位：克
      fat: nutritionTarget.fat || 67,          // 单位：克
      fiber: nutritionTarget.fiber || 25       // 单位：克
    };
    
    // 计算营养素差值
    const deficit = {
      calories: Math.max(0, targets.calories - consumed.calories),
      carbs: Math.max(0, targets.carbs - consumed.carbs),
      protein: Math.max(0, targets.protein - consumed.protein),
      fat: Math.max(0, targets.fat - consumed.fat),
      fiber: Math.max(0, targets.fiber - consumed.fiber)
    };
    
    // 标准化差值(转换为0-1的比例)
    const normalized = {
      calories: deficit.calories / targets.calories,
      carbs: deficit.carbs / targets.carbs,
      protein: deficit.protein / targets.protein,
      fat: deficit.fat / targets.fat,
      fiber: deficit.fiber / targets.fiber
    };
    
    // 权重设置
    const weights = {
      calories: 0.2,
      carbs: 0.2,
      protein: 0.3,
      fat: 0.2,
      fiber: 0.1
    };
    
    // 推荐主食(低GI值优先)
    let stapleRecommendations = await FoodGI.find({
      isStapleFood: true,
      giValue: { $lte: 60 } // 优先推荐低GI值主食
    }).sort({ giValue: 1 }).limit(10);
    
    // 如果低GI值主食不足3个，增加选择范围
    if (stapleRecommendations.length < 3) {
      stapleRecommendations = await FoodGI.find({
        isStapleFood: true
      }).sort({ giValue: 1 }).limit(10);
    }
    
    // 为主食打分
    stapleRecommendations = stapleRecommendations.map(food => {
      // 基于营养素差值和主食特性计算分数
      const score = 
        (normalized.calories * weights.calories * food.nutrition.calories / 100) +
        (normalized.carbs * weights.carbs * food.nutrition.carbs / 100) +
        (normalized.fiber * weights.fiber * food.nutrition.fiber * 2) + // 增加膳食纤维权重
        (1 - food.giValue / 100) * 0.5; // GI值低的加分
      
      return {
        ...food.toObject(),
        score: parseFloat(score.toFixed(2))
      };
    }).sort((a, b) => b.score - a.score);
    
    // 最多返回3个主食推荐
    stapleRecommendations = stapleRecommendations.slice(0, 3);
    
    // 推荐菜肴(蛋白质食物)
    let proteinRecommendations = await FoodGI.find({
      isStapleFood: false,
      category: { $in: ['protein', 'legumes'] }
    }).limit(10);
    
    // 为菜肴打分
    proteinRecommendations = proteinRecommendations.map(food => {
      // 基于营养素差值和蛋白质含量计算分数
      const score = 
        (normalized.calories * weights.calories * food.nutrition.calories / 100) +
        (normalized.protein * weights.protein * food.nutrition.protein * 2) + // 增加蛋白质权重
        (normalized.fat * weights.fat * food.nutrition.fat);
      
      return {
        ...food.toObject(),
        score: parseFloat(score.toFixed(2))
      };
    }).sort((a, b) => b.score - a.score);
    
    // 最多返回3个蛋白质推荐
    proteinRecommendations = proteinRecommendations.slice(0, 3);
    
    // 推荐蔬菜
    let vegetableRecommendations = await FoodGI.find({
      category: 'vegetables'
    }).limit(10);
    
    // 为蔬菜打分
    vegetableRecommendations = vegetableRecommendations.map(food => {
      // 基于营养素差值和蔬菜特性计算分数
      const score = 
        (normalized.fiber * weights.fiber * food.nutrition.fiber * 2) + // 增加膳食纤维权重
        (1 - normalized.carbs * 0.5); // 碳水少的蔬菜加分
      
      return {
        ...food.toObject(),
        score: parseFloat(score.toFixed(2))
      };
    }).sort((a, b) => b.score - a.score);
    
    // 最多返回3个蔬菜推荐
    vegetableRecommendations = vegetableRecommendations.slice(0, 3);
    
    // 返回推荐结果
    res.json({
      success: true,
      data: {
        nutritionDeficit: deficit,
        stapleRecommendations,
        proteinRecommendations,
        vegetableRecommendations,
        // 补充营养相关信息
        tips: [
          {
            type: 'general',
            content: '糖尿病患者应优先选择低GI值食物，控制主食量'
          },
          {
            type: 'meal_order',
            content: '建议先吃蔬菜和蛋白质食物，最后吃主食，有助于控制餐后血糖波动'
          }
        ]
      }
    });
  } catch (err) {
    console.error('获取食物推荐失败:', err.message);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

/**
 * @route   GET api/food/gi/:id
 * @desc    获取单个食物GI值数据
 * @access  Private
 */
router.get('/gi/:id', protect, async (req, res) => {
  try {
    const food = await FoodGI.findById(req.params.id);
    
    if (!food) {
      return res.status(404).json({
        success: false,
        message: '食物数据不存在'
      });
    }
    
    res.json({
      success: true,
      data: food
    });
  } catch (err) {
    console.error('获取食物GI值数据失败:', err.message);
    
    if (err.kind === 'ObjectId') {
      return res.status(404).json({
        success: false,
        message: '食物数据不存在'
      });
    }
    
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

/**
 * @route   POST api/food/gi
 * @desc    添加新的食物GI值数据
 * @access  Private (Admin)
 */
router.post('/gi', [
  protect,
  [
    check('name', '食物名称必填').not().isEmpty(),
    check('giValue', 'GI值必须为数字').isNumeric(),
    check('category', '食物类别必填').not().isEmpty()
  ]
], async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({
      success: false,
      errors: errors.array()
    });
  }
  
  try {
    // 验证管理员权限
    const user = await User.findById(req.user.id);
    if (!user || user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足，需要管理员权限'
      });
    }
    
    const {
      name,
      giValue,
      category,
      isStapleFood = false,
      nutrition = {},
      notes,
      benefits = []
    } = req.body;
    
    // 判断GI分类
    let giCategory = 'medium';
    if (giValue <= 55) giCategory = 'low';
    else if (giValue >= 70) giCategory = 'high';
    
    // 创建新的食物GI数据
    const newFood = new FoodGI({
      name,
      giValue,
      giCategory,
      category,
      isStapleFood,
      nutrition,
      notes,
      benefits
    });
    
    const food = await newFood.save();
    
    res.json({
      success: true,
      data: food
    });
  } catch (err) {
    console.error('添加食物GI值数据失败:', err.message);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

module.exports = router; 